<?php

if_get('/field_instances', function ()
{/*{{{*/
    list(
        $inputs['field_id'], $inputs['subject_instance_id']
    ) = input_list(
        'field_id', 'subject_instance_id'
    );

    $inputs = array_filter($inputs, 'not_null');

    $field_instances = dao('field_instance')->find_all_by_column($inputs);

    return [
        'count' => count($field_instances),
        'field_instances' => array_build($field_instances, function ($id, $field_instance) {
            return [
                null,
                [
                    'id' => $field_instance->id,
                    'field_display' => $field_instance->field->display_for_field_instances_field(),
                    'subject_instance_display' => $field_instance->subject_instance->display_for_field_instances_subject_instance(),
                    'create_time' => $field_instance->create_time,
                    'update_time' => $field_instance->update_time,
                ]
            ];
        }),
    ];
});/*}}}*/

if_post('/field_instances/add', function ()
{/*{{{*/

    $field_instance = field_instance::create(
        input_entity('field', null, 'field_id'),
        input_entity('subject_instance', null, 'subject_instance_id')
    );

    return [
        'id' => $field_instance->id,
    ];
});/*}}}*/

//todo::detail

if_post('/field_instances/update/*', function ($field_instance_id)
{/*{{{*/

    $field_instance = dao('field_instance')->find($field_instance_id);
    otherwise_error_code('FIELD_INSTANCE_NOT_FOUND', $field_instance->is_not_null());

    $field_instance->field = input_entity('field', null, 'field_id');
    $field_instance->subject_instance = input_entity('subject_instance', null, 'subject_instance_id');

    return true;
});/*}}}*/

if_post('/field_instances/delete/*', function ($field_instance_id)
{/*{{{*/
    $field_instance = dao('field_instance')->find($field_instance_id);
    otherwise_error_code('FIELD_INSTANCE_NOT_FOUND', $field_instance->is_not_null());

    $field_instance->delete();

    return true;
});/*}}}*/
